<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" id="searchFormId">
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            placeholder="请输入部门名称"
            v-model="searchParams.deptName"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleTreeList"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            placeholder="请输入联系电话"
            v-model="searchParams.phone"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleTreeList"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain @click="handleSearch" v-auth="['system:testDept:search']">搜索</el-button>
          <el-button type="danger" icon="refresh" plain @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:testDept:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:testDept:update']">
          <el-button type="success" icon="edit" plain @click="handleUpdate()" :disabled="single">修改</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:testDept:delete']">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" icon="Sort" plain @click="toggleExpandAll()">展开/折叠</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleTreeList"></KoiToolbar>
      </el-row>

      <br />
      <!-- 数据表格 -->
      <el-table
        v-if="refreshTreeTable"
        v-loading="loading"
        v-adaptiveTree
        border
        :data="tableList"
        @selection-change="handleSelectionChange"
        :default-expand-all="isExpandAll"
        row-key="deptId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        empty-text="暂时没有数据哟🌻"
       >
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="序号" prop="id" width="80px" align="center" type="index"></el-table-column>
         <el-table-column
           label="部门ID"
           prop="deptId"
           width="120px"
           align="center"
           :show-overflow-tooltip="true"
         ></el-table-column>
         <el-table-column
           label="父部门ID"
           prop="parentId"
           width="120px"
           align="center"
           :show-overflow-tooltip="true"
         ></el-table-column>
         <el-table-column
           label="部门名称"
           prop="deptName"
           width="120px"
           align="center"
           :show-overflow-tooltip="true"
         ></el-table-column>
         <el-table-column
           label="是否展开（0是 1否)"
           prop="isSpread"
           width="120px"
           align="center"
           :show-overflow-tooltip="true"
         ></el-table-column>
         <el-table-column
           label="领导"
           prop="leader"
           width="120px"
           align="center"
           :show-overflow-tooltip="true"
         ></el-table-column>
         <el-table-column
           label="联系电话"
           prop="phone"
           width="120px"
           align="center"
           :show-overflow-tooltip="true"
         ></el-table-column>
         <el-table-column
           label="邮箱"
           prop="email"
           width="120px"
           align="center"
           :show-overflow-tooltip="true"
         ></el-table-column>
         <el-table-column
           label="部门状态（0启用 1停用）"
           prop="deptStatus"
           width="120px"
           align="center"
           :show-overflow-tooltip="true"
         ></el-table-column>
         <el-table-column
           label="显示顺序"
           prop="sorted"
           width="120px"
           align="center"
           :show-overflow-tooltip="true"
         ></el-table-column>
         <el-table-column
           label="备注"
           prop="remark"
           width="120px"
           align="center"
           :show-overflow-tooltip="true"
         ></el-table-column>
         <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
         <el-table-column label="操作" align="center" width="120" fixed="right" v-auth="['system:testDept:update', 'system:testDept:delete']">
           <template #default="{ row }">
             <el-tooltip content="修改🌻" placement="top">
               <el-button
                  type="primary"
                  icon="Edit"
                  circle
                  plain
                  @click="handleUpdate(row)"
                  v-auth="['system:testDept:update']"
               ></el-button>
             </el-tooltip>
             <el-tooltip content="删除🌻" placement="top">
               <el-button
                 type="danger"
                 icon="Delete"
                 circle
                 plain
                 @click="handleDelete(row)"
                 v-auth="['system:testDept:delete']"
               ></el-button>
             </el-tooltip>
           </template>
         </el-table-column>
       </el-table>
       <!-- 添加 OR 修改 -->
       <KoiDrawer
         ref="koiDrawerRef"
         :title="title"
         @koiConfirm="handleConfirm"
         @koiCancel="handleCancel"
         :loading="confirmLoading"
       >
         <template #content>
           <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
             <el-row>
               <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                 <el-form-item label="部门ID" prop="deptId">
                   <el-input v-model="form.deptId" placeholder="请输入部门ID" clearable />
                 </el-form-item>
               </el-col>
               <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                 <el-form-item label="父部门ID" prop="parentId">
                   <!-- 级联选择框 -->
                   <el-cascader
                     placeholder="请选择上级数据"
                     v-model="form.parentId"
                     :options="cascaderOptions"
                     :props="{
                       expandTrigger: 'hover',
                       emitPath: false,
                       checkStrictly: true
                     }"
                     filterable
                     clearable
                     style="width: 540px"
                   >
                     <template #default="{ node, data }">
                       <span>{{ data.label }}</span>
                       <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                     </template>
                   </el-cascader>
                 </el-form-item>
               </el-col>
               <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                 <el-form-item label="部门名称" prop="deptName">
                   <el-input v-model="form.deptName" placeholder="请输入部门名称" clearable />
                 </el-form-item>
               </el-col>
               <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                 <el-form-item label="是否展开（0是 1否)" prop="isSpread">
                   <!-- 单选框需要字典类型，若没有，则只生成示例 -->
                   <el-radio-group v-model="form.isSpread">
                     <el-radio border label="0">启用</el-radio>
                     <el-radio border label="1">停用</el-radio>
                   </el-radio-group>
                 </el-form-item>
               </el-col>
               <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                 <el-form-item label="领导" prop="leader">
                   <el-input v-model="form.leader" placeholder="请输入领导" clearable />
                 </el-form-item>
               </el-col>
               <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                 <el-form-item label="联系电话" prop="phone">
                   <el-input v-model="form.phone" placeholder="请输入联系电话" clearable />
                 </el-form-item>
               </el-col>
               <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                 <el-form-item label="邮箱" prop="email">
                   <el-input v-model="form.email" placeholder="请输入邮箱" clearable />
                 </el-form-item>
               </el-col>
               <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                 <el-form-item label="部门状态（0启用 1停用）" prop="deptStatus">
                   <!-- 下拉框需要字典类型，若没有，则只生成示例 -->
                   <el-select placeholder="请选择部门状态（0启用 1停用）" v-model="form.deptStatus" clearable>
                     <el-option label="启用" value="0" />
                     <el-option label="停用" value="1" />
                   </el-select>
                 </el-form-item>
               </el-col>
               <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                 <el-form-item label="显示顺序" prop="sorted">
                   <el-input-number v-model="form.sorted" placeholder="请输入数字" :min="1" clearable />
                 </el-form-item>
               </el-col>
               <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                 <el-form-item label="备注" prop="remark">
                   <el-input v-model="form.remark" placeholder="请输入备注" clearable />
                 </el-form-item>
               </el-col>
             </el-row>
           </el-form>
         </template>
       </KoiDrawer>
     </el-card>
</div>
</template>

<script setup lang="ts" name="testDeptPage">
import { nextTick, ref, reactive, onMounted } from "vue";
import { koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning, koiMsgBox, koiMsgInfo } from "@/utils/koi.ts";
import { handleTree } from "@/utils/index.ts";
import {
    list,
    cascaderList,
    getById,
    add,
    update,
    deleteById,
    batchDelete
} from "@/api/test/dept/index.ts";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref({
  deptName: "",
  phone: "",
});
// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    deptName: "",
    phone: "",
  };
};
/** 搜索 */
const handleSearch = () => {
  handleTreeList();
};
/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleTreeList();
};

/** 树形表格查询 */
const handleTreeList = async () => {
  try {
    tableList.value = []; // 重置表格数据
    loading.value = true;
    const res: any = await list(searchParams.value);
    tableList.value = handleTree(res.data, "deptId", "parentId");
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
};

/** 数据表格 */
const handleTableData = async () => {
  try {
    const res: any = await list(searchParams.value);
    tableList.value = handleTree(res.data, "deptId", "parentId");
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
};

onMounted(() => {
  // 获取数据表格数据
  handleTreeList();
});

const ids = ref([]); // 选中数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用
/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

// 级联下拉框
let cascaderOptions = ref<any>([]);
/** 级联下拉框[后端自行实现] */
const handleCascader = async () => {
  try {
    cascaderOptions.value = [];
    const res: any = await cascaderList();
    cascaderOptions.value = handleTree(res.data, "value");
    cascaderOptions.value.unshift({
      label: "最顶级数据",
      value: "0",
      parentId: "-1"
    });
  } catch (error) {
    console.log(error);
    koiMsgError("部门级联数据查询失败，请重试🌻");
  }
};

// 重新渲染表格状态
const refreshTreeTable = ref(true);
// 是否展开，默认折叠
const isExpandAll = ref(false);
/** 展开/折叠 */
const toggleExpandAll = () => {
  refreshTreeTable.value = false;
  isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
      refreshTreeTable.value = true;
    });
};
/** 添加 */
const handleAdd = () => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "添加操作";
  handleCascader();
  form.value.parentId = "0";
  koiDrawerRef.value.koiOpen();
  koiMsgInfo("添加🌻");
};

// 最顶级不可编辑
/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据🌻");
    return;
  }
  try {
    const res: any = await getById(id);
    form.value = res.data;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据获取失败，请刷新重试🌻");
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "修改操作";
  const id = row ? row.id : ids.value[0];
  if (id == null || id == "") {
    koiMsgError("请选择需要修改的数据🌻");
    return;
  }
  handleCascader();
  // 回显数据
  handleEcho(id);
  koiDrawerRef.value.koiOpen();
  koiMsgInfo("修改🌻");
};

/** 添加 AND 修改弹出框 */
const koiDrawerRef = ref();
// 标题
const title = ref('部门表');
// form表单Ref
const formRef = ref<any>();
// form表单
let form = ref<any>({
  deptId: "",
  parentId: "",
  deptName: "",
  isSpread: "",
  leader: "",
  phone: "",
  email: "",
  deptStatus: "",
  sorted: "",
  remark: "",
});
/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    deptId: null,
    parentId: null,
    deptName: null,
    isSpread: null,
    leader: null,
    phone: null,
    email: null,
    deptStatus: null,
    sorted: null,
    remark: null,
  };
};
/** 表单规则 */
const rules = reactive({
  deptId: [{ required: true, message: "请输入部门ID", trigger: "blur" }],
  parentId: [{ required: true, message: "请输入父部门ID", trigger: "blur" }],
  deptName: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
  isSpread: [{ required: true, message: "请输入是否展开（0是 1否)", trigger: "blur" }],
  leader: [{ required: true, message: "请输入领导", trigger: "blur" }],
  phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  deptStatus: [{ required: true, message: "请输入部门状态（0启用 1停用）", trigger: "blur" }],
  sorted: [{ required: true, message: "请输入显示顺序", trigger: "blur" }],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      if (form.value.id != null && form.value.id != "") {
        try {
          await update(form.value);
          koiNoticeSuccess("修改成功🌻");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleTreeList();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("修改失败，请刷新重试🌻");
        }
      } else {
        try {
          await add(form.value);
          koiNoticeSuccess("添加成功🌻");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleTreeList();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("添加失败，请刷新重试🌻");
        }
      }
      } else {
         koiMsgError("验证失败，请检查填写内容🌻");
         confirmLoading.value = false;
      }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.id;
  if (id == null || id == "") {
    koiMsgWarning("请选中需要删除的数据🌻");
    return;
  }
  koiMsgBox("您确认删除该数据么？删除后将无法进行恢复？")
    .then(async () => {
      try {
        await deleteById(id);
        koiNoticeSuccess("删除成功🌻");
        handleTableData();
      } catch (error) {
        console.log(error);
      }
    })
    .catch(() => {
      koiMsgError("已取消🌻");
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgInfo("请选择需要删除的数据🌻");
    return;
  }
    koiMsgBox("您确认进行批量删除么？删除后将无法进行恢复？")
      .then(async () => {
        try {
          await batchDelete(ids.value);
          koiNoticeSuccess("批量删除成功🌻");
          handleTableData();
        } catch (error) {
          console.log(error);
        }
      })
      .catch(() => {
        koiMsgError("已取消🌻");
      });
};
</script>

<style lang="scss" scoped></style>
